<template>
  <div>
    <canvas ref="canvas1" style="display: block;" :width="width" :height="height"></canvas>  
    <canvas ref="canvas" :width="width" :height="height" style="display: none;"></canvas>
  </div>
</template>

<script>
export default {
  data() {  
    return {  
      ctx: null,
      isLoadingComplete: false, 
    };  
  },  
  props: ['videoSrc', 'time', 'width', 'height'],
  mounted() {
    this.ctx = this.$refs.canvas1.getContext('2d');  
    this.drawBackground();  
    // this.drawBox();  
    // this.drawLoadingIcon(); 
    this.generateThumbnail();
  },
  methods: {
    drawBackground() {  
      this.ctx.fillStyle = '#f5f5f5'; // 背景颜色  
      this.ctx.fillRect(0, 0, this.$refs.canvas1.width, this.$refs.canvas1.height);  
      // 设置文本样式  
      this.ctx.fillStyle = '#456789'; // 文本颜色为黑色  
      this.ctx.font = 'bold 20px sans-serif'; // 设置字体为粗体，大小为24像素，字体族为无衬线字体  
  
      // 计算文本的宽度和高度  
      const textWidth = this.ctx.measureText('缩略图').width;  
      const textHeight = 20; // 假设字体大小为24像素  
  
      // 在背景上绘制文本“缩略图”  
      this.ctx.fillText('缩略图', (this.$refs.canvas1.width - textWidth) / 2, (this.$refs.canvas1.height - textHeight) / 2);  

    },
    generateThumbnail() {
      const video = document.createElement('video');
      video.src = this.videoSrc;
      video.currentTime = this.time;
      video.addEventListener('loadeddata', () => {
        const canvas = this.$refs.canvas;
        const context = canvas.getContext('2d');
        context.drawImage(video, 0, 0, this.width, this.height);
        this.isLoadingComplete = true;  
      });
    },
  },
  watch: {  
    // 监听isLoadingComplete的变化，以便在数据加载完成后切换canvas的显示状态  
    isLoadingComplete(newValue) {  
      if (newValue) {  
        // 数据加载完成，隐藏加载界面，显示数据展示界面  
        this.$refs.canvas1.style.display = 'none';  
        this.$refs.canvas.style.display = 'block';  
      } else {  
        // 数据加载未完成，显示加载界面，隐藏数据展示界面  
        this.$refs.canvas1.style.fillText = '#000'; // 设置文本颜色为黑色  
        this.$refs.canvas1.style.textAlign = 'center'; // 文本居中对齐  
        this.$refs.canvas1.style.textBaseline = 'middle'; // 文本垂直居中  
        this.$refs.canvas1.style.fontFamily = 'sans-serif'; // 设置字体族为无衬线字体  
        this.$refs.canvas1.style.fontWeight = 'bold'; // 设置字体加粗  
        this.$refs.canvas1.style.fontSize = '24px'; // 设置字体大小为24像素  
        this.$refs.canvas1.style.fillText('缩略图', this.$refs.canvas1.width / 2, this.$refs.canvas1.height / 2); // 在canvas中心位置绘制文本“缩略图”  
      }  
    },  
  },
};

</script>